﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Xml;

namespace DrawingScreen.Objects
{
    public class CLine: CDrawingObject
    {
        public int x1;
        public int y1;
        public int x2;
        public int y2;

        public Pen pen = new Pen(Color.Black, 5);

        public override void Draw(Graphics g)
        {
            g.DrawLine(pen, new Point(this.x1, this.y1), 
                new Point(this.x2, this.y2));
        }

        public override XmlNode convertToXmlNode(XmlDocument doc)
        {
            try
            {
                XmlElement eleObject = doc.CreateElement("OBJECT");

                XmlAttribute attObjectID = doc.CreateAttribute("id");
                attObjectID.Value = CDrawingObject.LINE_ID.ToString();
                eleObject.Attributes.Append(attObjectID);

                //////////////////////////////////////////////////////////////
                XmlElement eleLine = doc.CreateElement("LINE");

                XmlAttribute attX1 = doc.CreateAttribute("x1");
                attX1.Value = x1.ToString();
                eleLine.Attributes.Append(attX1);

                XmlAttribute attY1 = doc.CreateAttribute("y1");
                attY1.Value = y1.ToString();
                eleLine.Attributes.Append(attY1);

                XmlAttribute attX2 = doc.CreateAttribute("x2");
                attX2.Value = x2.ToString();
                eleLine.Attributes.Append(attX2);

                XmlAttribute attY2 = doc.CreateAttribute("y2");
                attY2.Value = y2.ToString();
                eleLine.Attributes.Append(attY2);

                XmlElement elePen = Global.CreateXmlElementFromPen(doc, pen);
                eleLine.AppendChild(elePen);

                //////////////////////////////////////////////////////////////

                eleObject.AppendChild(eleLine);

                return eleObject;
            }
            catch
            {
                return null;
            }
        }

        public static CLine CreateDrawingObject(XmlElement eleObject)
        {
            try
            {
                XmlElement eleLine = (XmlElement)eleObject.FirstChild;

                CLine l = new CLine();
                l.x1 = Int32.Parse(eleLine.Attributes["x1"].Value);
                l.y1 = Int32.Parse(eleLine.Attributes["y1"].Value);
                l.x2 = Int32.Parse(eleLine.Attributes["x2"].Value);
                l.y2 = Int32.Parse(eleLine.Attributes["y2"].Value);

                Pen pen = Global.CreatePenFromXmlElement((XmlElement)eleLine.FirstChild);

                if (pen != null)
                {
                    l.pen = pen;
                }

                return l;

            }
            catch
            {
                return null;
            }
        }
    }
}
